<?php defined('SYSPATH') or die('No direct access allowed.');

	class Model_Filtersearch extends Model{
		
		public $filters = array();
			
		
		public function addFilter($filter){
			array_push($this->filters,$filter);
			return;
		}
		
		private function createQueryCondition(){
			if (!(count($this->filters)> 0)) return false;
			
			$where = array();
			foreach($this->filters as $filter){
				$where[] = $filter->toString();
			}
			
			return implode(" AND ", $where);
		}
		
		public function buildQuery($page_number=false){
			
			$query = "SELECT DISTINCT ";
			$query.= "	analysis.id AS 'id',";
			$query.= "	analysis.analysis_date AS 'Fecha',";
			$query.= "  CONCAT(patients.surname,', ',patients.name) AS 'Paciente',";
			$query.= "	analysis_result.aod_value AS 'AOD',";
			$query.= "	analysis_result.aos_value AS 'AOS',";
			$query.= "	analysis_result.iar_value AS 'IAR' ";
			$query.= "FROM analysis ";
			$query.= "JOIN patients ON analysis.patient_id = patients.id ";
			$query.= "JOIN clinical_information ON analysis.clinical_info_id = clinical_information.id ";
			$query.= "JOIN analysis_result ON analysis.analysis_result_id = analysis_result.id ";
			$query.= "JOIN pathology_by_patient ON pathology_by_patient.patient_id = patients.id ";
			$query.= "JOIN pathologies ON pathology_by_patient.patient_id = patients.id ";
			
			if ($condition = $this->createQueryCondition()) $query.= " WHERE ".$condition;
			
			return $query;
			
		}
		
		#SELECT DISTINCT
		#	a.id AS 'id',
		#	a.analysis_date AS 'Fecha',
		#	CONCAT(p.surname,", ",p.name) AS 'Paciente',
		#	ar.aod_value AS 'AOD',
		#	ar.aos_value AS 'AOS',
		#	ar.iar_value AS 'IAR'
		#FROM
		#	analysis a
		#JOIN
		#	patients p ON a.patient_id = p.id
		#JOIN
		#	clinical_information ci ON a.clinical_info_id = ci.id
		#JOIN
		#	analysis_result ar ON a.analysis_result_id = ar.id
		#JOIN
		#	pathology_by_patient pp ON pp.patient_id = p.id
		#JOIN
		#	pathologies pt ON pp.pathology_id = pt.id
		#join
		#	habit_patients h ON p.habits_id = h.id
		
	}
?>